from django.db.models import ProtectedError
from datetime import datetime
from django.contrib.auth import authenticate, get_user_model
from rest_framework.request import Request
from rest_framework import viewsets, permissions
from rest_framework.permissions import IsAuthenticated
from apps.vadmin.assets.enums import AssetsEnum,AssignedTypeEnum
from django.db.models import F
from apps.vadmin.assets.filters import AccessoriesFilter,  AssetsFilter, \
        CategoriesFilter, CategoryTotalReportFilter,  \
        ComponentsFilter, ConsumablesFilter,\
        DepreciationsFilter, KitsFilter, \
        LicensesFilter, MaintenancesFilter, \
        ManufacturersFilter, ModelsFilter,\
        SuppliersFilter, UploadsFilter,\
        UserCheckoutReportFilter
from apps.vadmin.assets.models.accessories import Accessories
from apps.vadmin.assets.models.assets import Assets
from apps.vadmin.assets.models.components import Components
from apps.vadmin.assets.models.consumables import Consumables
from apps.vadmin.assets.models.depreciations import Depreciations
from apps.vadmin.assets.models.locations import Locations
from apps.vadmin.assets.serializers import LocationsSerializer
from apps.vadmin.assets.filters import LocationsFilter
from apps.vadmin.assets.models.kits import Kits
from apps.vadmin.assets.models.kits_accessories import KitsAccessories
from apps.vadmin.assets.models.kits_consumables import KitsConsumables
from apps.vadmin.assets.models.kits_licenses import KitsLicenses
from apps.vadmin.assets.models.kits_models import KitsModels
from apps.vadmin.assets.models.licenses import Licenses
from apps.vadmin.assets.models.maintenances import Maintenances
from apps.vadmin.assets.models.report import AssetStatusReport, CategoryTotalReport, UserCheckoutReport
from apps.vadmin.assets.models.uploads import Uploads
from apps.vadmin.op_drf.filters import DataLevelPermissionsFilter

from apps.vadmin.op_drf.response import SuccessResponse, ErrorResponse
from apps.vadmin.assets.models.categories import Categories
from apps.vadmin.assets.models.models import Models 
from apps.vadmin.assets.models.suppliers import Suppliers 
from apps.vadmin.assets.models.manufacturers import Manufacturers 
from apps.vadmin.op_drf.viewsets import CustomModelViewSet, GenericViewSet
from apps.vadmin.assets.serializers import AccessoriesCreateUpdateSerializer, AccessoriesSerializer,\
        AssetStatusReportSerializer, AssetsCreateUpdateSerializer, \
        AssetsSerializer, CategoriesSerializer,\
        CategoriesCreateUpdateSerializer, CategoryTotalReportSerializer, \
        ComponentsCreateUpdateSerializer, ComponentsSerializer, \
        ConsumablesCreateUpdateSerializer, ConsumablesSerializer, \
        DepreciationsSerializer, KitsAccessoriesSerializer, \
        KitsConsumablesSerializer, KitsCreateUpdateSerializer, \
        KitsLicensesSerializer, KitsModelsSerializer, \
        KitsSerializer, LicensesCreateUpdateSerializer, \
        LicensesSerializer, MaintenancesSerializer,\
        SuppliersSerializer, UploadsSerializer,\
        UserCheckoutReportSerializer
from apps.vadmin.assets.serializers import ImportAssetsSerializer
from apps.vadmin.assets.serializers import ExportAssetsSerializer,ExportAccessoriesSerializer,ExportComponentsSerializer,\
        ExportConsumablesSerializer,ExportLicensesSerializer,ExportLocationsSerializer,ExportModelsSerializer,\
        ExportCategoriesSerializer,ExportDepreciationsSerializer,ExportSuppliersSerializer,ExportManufacturersSerializer
from apps.vadmin.assets.serializers import ModelsSerializer,ModelsCreateUpdateSerializer,ManufacturersSerializer
from apps.vadmin.permission.models.users import UserProfile
from apps.vadmin.permission.permissions import CommonPermission
from apps.vadmin.utils.exceptions import APIException


class MyPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        # 在这里实现你的权限逻辑
        return True  # 忽略权限，总是允许访问
'''
/categories/        GET     -显示所有类别
/categories/        post    -新增类别
/categories/{id}/   GET     -显示单个类别
/categories/{id}/   PUT     -编辑单个类别
/categories/{id}/   DELETE  -删除单个类别
'''
class CategoriesModelViewSet(CustomModelViewSet):
    """
    分类模型的CRUD视图
    """
    #permission_classes = [MyPermission]  # 指定权限类
    permission_classes = [IsAuthenticated]
    queryset = Categories.objects.all()
    serializer_class = CategoriesSerializer
    create_serializer_class = CategoriesCreateUpdateSerializer
    update_serializer_class = CategoriesCreateUpdateSerializer
    filter_class = CategoriesFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    # update_extra_permission_classes = (CommonPermission,)
    # destroy_extra_permission_classes = (CommonPermission,)
    # create_extra_permission_classes = (CommonPermission,)
    search_fields = ('name',)
    ordering = 'create_datetime'  # 默认排序

    import_serializer_class = ExportCategoriesSerializer
    import_field_data = {
            'id':'分类ID', 
            'name':'分类名称',
            'create_datetime':'创建时间', 
            'category_type':'类型' }

    export_serializer_class = ExportCategoriesSerializer
    export_field_data = ['分类ID', '分类名称', '创建时间', '类型' ]

    def destroy(self, request, *args, **kwargs):
        try:
            super().destroy(request,*args,**kwargs)
        except ProtectedError:
            raise APIException(message='该分类已被关联使用,不能删除只能修改')

'''
/models/        GET     -显示所有型号
/models/        post    -新增型号
/models/{id}/   GET     -显示单个型号
/models/{id}/   PUT     -编辑单个型号
/models/{id}/   DELETE  -删除单个型号
'''
class ModelsModelViewSet(CustomModelViewSet):
    """
    型号模型的CRUD视图
    """
    permission_classes = [IsAuthenticated]
    queryset = Models.objects.all()
    serializer_class = ModelsSerializer
    create_serializer_class = ModelsCreateUpdateSerializer
    update_serializer_class = ModelsCreateUpdateSerializer
    filter_class = ModelsFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    # update_extra_permission_classes = (CommonPermission,)
    # destroy_extra_permission_classes = (CommonPermission,)
    # create_extra_permission_classes = (CommonPermission,)
    search_fields = ('name',)
    ordering = 'create_datetime'  # 默认排序

    import_serializer_class = ExportModelsSerializer
    import_field_data = {
            'id':'型号ID', 
            'name':'型号名称',
            'create_datetime':'创建时间',
            'model_number':'型号编码',
            'eol':'寿命',
            'requestable':'是否可申请',
            'notes':'备注',
            'category_id':'分类Id',
            'manufacturer_id':'制造商Id'
            }

    export_serializer_class = ExportModelsSerializer
    export_field_data = ['型号ID', '型号名称', '创建时间', '型号编码', '寿命',
                         '是否可申请', '备注', '分类Id', '制造商Id']

    def destroy(self, request, *args, **kwargs):
        try:
            super().destroy(request,*args,**kwargs)
        except ProtectedError:
            raise APIException(message='该型号已被关联使用,不能删除只能修改')



'''
/suppliers/        GET     -显示所有
/suppliers/        post    -新增一个
/suppliers/{id}/   GET     -显示单个
/suppliers/{id}/   PUT     -编辑单个
/suppliers/{id}/   DELETE  -删除单个
'''
class SuppliersModelViewSet(CustomModelViewSet):
    """
    供应商模型的CRUD视图
    """
    permission_classes = [IsAuthenticated]
    queryset = Suppliers.objects.all()
    serializer_class = SuppliersSerializer
    # create_serializer_class = SuppliersCreateUpdateSerializer
    # update_serializer_class = SuppliersCreateUpdateSerializer
    filter_class = SuppliersFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    # update_extra_permission_classes = (CommonPermission,)
    # destroy_extra_permission_classes = (CommonPermission,)
    # create_extra_permission_classes = (CommonPermission,)
    search_fields = ('name',)
    import_serializer_class = ExportSuppliersSerializer 
    import_field_data = {
                'id':'供应商ID', 
                'name':'供应商名称',
                'create_datetime':'创建时间', 
                'state':'省',
                'city':'市',
                'address':'区',
                'address2':'地址', 
                'contact':'联系人',
                'phone':'联系电话', 
                'email':'邮箱',
                'fax':'传真',
                'url':'官网地址',
                'zip':'邮编',
                'notes':'备注'}
    export_serializer_class = ExportSuppliersSerializer
    export_field_data = ['供应商ID', '供应商名称', '创建时间', '省', '市',
                         '区', '地址', '联系人', '电话','邮箱',
                         '传真','官网地址','邮编','备注']

    def destroy(self, request, *args, **kwargs):
        try:
            super().destroy(request,*args,**kwargs)
        except ProtectedError:
            raise APIException(message='该供应商已被关联使用,不能删除只能修改')

        
'''
/manufacturers/        GET     -显示所有
/manufacturers/        post    -新增一个
/manufacturers/{id}/   GET     -显示单个
/manufacturers/{id}/   PUT     -编辑单个
/manufacturers/{id}/   DELETE  -删除单个
'''
class ManufacturersModelViewSet(CustomModelViewSet):
    """
    制造商模型的CRUD视图
    """
    permission_classes = [IsAuthenticated]
    queryset = Manufacturers.objects.all()
    serializer_class = ManufacturersSerializer
    # create_serializer_class = SuppliersCreateUpdateSerializer
    # update_serializer_class = SuppliersCreateUpdateSerializer
    filter_class = ManufacturersFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    # update_extra_permission_classes = (CommonPermission,)
    # destroy_extra_permission_classes = (CommonPermission,)
    # create_extra_permission_classes = (CommonPermission,)
    search_fields = ('name',)
    import_serializer_class = ExportManufacturersSerializer
    import_field_data = {
            'id':'制造商Id', 
            'name':'制造商名称',
            'create_datetime':'创建时间', 
            'url':'官网url', 
            'support_url':'技术支持网址',
            'support_phone':'技术支持电话',
            'support_email':'技术支持邮箱'
            }

    export_serializer_class = ExportManufacturersSerializer
    export_field_data = ['制造商Id', '制造商名称','创建时间', '官网url', '技术支持网址','技术支持电话','技术支持邮箱']
    
    def destroy(self, request, *args, **kwargs):
        try:
            super().destroy(request,*args,**kwargs)
        except ProtectedError:
            raise APIException(message='该制造商已被关联使用,不能删除只能修改')

'''
/depreciations/        GET     -显示所有
/depreciations/        post    -新增一个
/depreciations/{id}/   GET     -显示单个
/depreciations/{id}/   PUT     -编辑单个
/depreciations/{id}/   DELETE  -删除单个
'''
class DepreciationsModelViewSet(CustomModelViewSet):
    '''
    折旧模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Depreciations.objects.all()
    serializer_class = DepreciationsSerializer
    filter_class = DepreciationsFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    search_fields = ('name',)

    import_serializer_class = ExportDepreciationsSerializer
    import_field_data = {
            'id':'ID', 
            'name':'名称', 
            'create_datetime':'创建时间', 
            'months':'月份', 
            'depreciation_min':'折后价值'}

    export_serializer_class = ExportDepreciationsSerializer
    export_field_data = ['ID', '名称', '创建时间', '月份', '折后价值']

    def destroy(self, request, *args, **kwargs):
        try:
            super().destroy(request,*args,**kwargs)
        except ProtectedError:
            raise APIException(message='该折旧信息已被关联使用,不能删除只能修改')

'''
/assets/        GET     -显示所有
/assets/        post    -新增一个
/assets/{id}/   GET     -显示单个
/assets/{id}/   PUT     -编辑单个
/assets/{id}/   DELETE  -删除单个
'''
class AssetsModelViewSet(CustomModelViewSet):
    '''
    资产模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Assets.objects.all()
    serializer_class = AssetsSerializer
    create_serializer_class = AssetsCreateUpdateSerializer
    update_serializer_class = AssetsCreateUpdateSerializer
    filter_class = AssetsFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    import_serializer_class = ImportAssetsSerializer
    import_field_data = {
            'id':'资产ID', 
            'name':'名称', 
            'asset_tag':'标签', 
            'serial':'序列号', 
            'purchase_date':'采购日期', 
            'asset_eol_date':'寿命截止日期',
            'purchase_cost':'采购价格', 
            'order_number':'订单号',
            'notes':'备注',
            'physical':'是否物理设备',
            'warranty_months':'质保月份',
            'depreciate':'是否会折旧',
            'requestable':'是否可申请',
            'last_checkout':'最后一次借出时间',
            'expected_checkin':'预期归还日期',
            'assigned_type':'借出类型',
            'last_audit_date':'上次盘点日期',
            'next_audit_date':'下次盘点日期',
            'checkin_counter':'归还次数',
            'checkout_counter':'借出次数',
            'requests_counter':'申请次数',
            'byod':'是否是自带设备',
            'model_id':'型号Id',
            'status':'资产状态',
            'supplier_id':'供应商Id',
            'assigned_to_id':'借出目标Id',
            'assigned_to_name':'借出目标',
            'location_id':'位置Id'}

    export_serializer_class = ExportAssetsSerializer
    export_field_data = ['资产ID', '名称', '标签', '序列号', '采购日期', '寿命截止日期',
                         '采购价格', '订单号','备注','是否物理设备','质保月份','是否会折旧',
                         '是否可申请','最后一次借出时间','预期归还日期','借出类型','上次盘点日期','下次盘点日期','归还次数',
                         '借出次数','申请次数','是否是自带设备','型号Id','资产状态','供应商Id','借出目标Id','借出目标','位置Id']
    search_fields = ('name',)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        # 更新删除字段
        instance.deleted_datetime = datetime.now() 
        instance.save()
        return SuccessResponse()


'''
/accessories/        GET     -显示所有
/accessories/        post    -新增一个
/accessories/{id}/   GET     -显示单个
/accessories/{id}/   PUT     -编辑单个
/accessories/{id}/   DELETE  -删除单个
'''
class AccessoriesModelViewSet(CustomModelViewSet):
    '''
    资产模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Accessories.objects.all()
    serializer_class = AccessoriesSerializer
    create_serializer_class = AccessoriesCreateUpdateSerializer
    update_serializer_class = AccessoriesCreateUpdateSerializer
    filter_class = AccessoriesFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    search_fields = ('name',)
    import_serializer_class = ExportAccessoriesSerializer
    import_field_data = {
            'id':'附属品ID', 
            'name':'名称', 
            'create_datetime':'创建时间', 
            'qty':'数量', 
            'requestable':'是否可申请',
            'purchase_date':'采购日期',
            'purchase_cost':'采购价格',
            'order_number':'订单号',
            'min_amt':'最小报警数量',
            'model_number':'型号编码',
            'notes':'备注',
            'category_id':'分类Id',
            'manufacturer_id':'制造商Id',
            'supplier_id':'供应商Id',
            'checkout_qty':'借出数量',
            'location_id':'位置Id'}

    export_serializer_class = ExportAccessoriesSerializer
    export_field_data = ['附属品ID', '名称', '创建时间', '数量', '是否可申请', '采购日期',
                         '采购价格', '订单号','最小报警数量','型号编码','备注','分类Id',
                         '制造商Id','供应商Id','借出数量','位置Id']


'''
/components/        GET     -显示所有
/components/        post    -新增一个
/components/{id}/   GET     -显示单个
/components/{id}/   PUT     -编辑单个
/components/{id}/   DELETE  -删除单个
'''
class ComponentsModelViewSet(CustomModelViewSet):
    '''
    资产模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Components.objects.all()
    serializer_class = ComponentsSerializer
    create_serializer_class = ComponentsCreateUpdateSerializer
    update_serializer_class = ComponentsCreateUpdateSerializer
    filter_class = ComponentsFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    search_fields = ('name',)

    import_serializer_class = ExportComponentsSerializer 
    import_field_data = {
            'id':'组件ID',
            'name':'名称',
            'serial':'序列号',
            'create_datetime':'创建时间', 
            'qty':'数量', 
            'purchase_date':'采购日期',
            'purchase_cost':'采购价格',
            'order_number':'订单号',
            'min_amt':'最小报警数量',
            'notes':'备注',
            'category_id':'分类Id',
            'manufacturer_id':'制造商Id',
            'supplier_id':'供应商Id',
            'checkout_qty':'借出数量',
            'location_id':'位置Id'
            } 
    export_serializer_class = ExportComponentsSerializer
    export_field_data = ['组件ID', '名称', '序列号','创建时间', '数量', '采购日期',
                         '采购价格', '订单号','最小报警数量','备注','分类Id',
                         '制造商Id','供应商Id','借出数量','位置Id']

'''
/components/        GET     -显示所有
/components/        post    -新增一个
/components/{id}/   GET     -显示单个
/components/{id}/   PUT     -编辑单个
/components/{id}/   DELETE  -删除单个
'''
class ConsumablesModelViewSet(CustomModelViewSet):
    '''
    消耗品模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Consumables.objects.all()
    serializer_class = ConsumablesSerializer
    create_serializer_class = ConsumablesCreateUpdateSerializer
    update_serializer_class = ConsumablesCreateUpdateSerializer
    filter_class = ConsumablesFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    search_fields = ('name',)

    import_serializer_class = ExportConsumablesSerializer
    import_field_data = {
            'id':'消耗品ID', 
            'name':'名称',
            'item_no':'编号',
            'create_datetime':'创建时间', 
            'qty':'数量', 
            'requestable':'是否可申请',
            'purchase_date':'采购日期',
            'purchase_cost':'采购价格',
            'order_number':'订单号',
            'min_amt':'最小报警数量',
            'model_number':'型号编码',
            'notes':'备注',
            'category_id':'分类Id', 
            'manufacturer_id':'制造商Id',
            'supplier_id':'供应商Id',
            'checkout_qty':'借出数量',
            'location_id':'位置Id'
            }

    export_serializer_class = ExportConsumablesSerializer
    export_field_data = ['消耗品ID', '名称', '编号','创建时间', '数量','是否可申请' ,'采购日期',
                         '采购价格', '订单号','最小报警数量','型号编码','备注','分类Id',
                         '制造商Id','供应商Id','借出数量','位置Id']


'''
/licenses/        GET     -显示所有
/licenses/        post    -新增一个
/licenses/{id}/   GET     -显示单个
/licenses/{id}/   PUT     -编辑单个
/licenses/{id}/   DELETE  -删除单个
'''
class LicensesModelViewSet(CustomModelViewSet):
    '''
    许可证模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Licenses.objects.all()
    serializer_class = LicensesSerializer
    create_serializer_class = LicensesCreateUpdateSerializer
    update_serializer_class = LicensesCreateUpdateSerializer
    filter_class = LicensesFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    search_fields = ('name',)

    import_serializer_class = ExportLicensesSerializer 
    import_field_data = {
            'id':'软件许可ID', 
            'name':'名称',
            'serial':'序列号',
            'create_datetime':'创建时间', 
            'seats':'授权数量', 
            'purchase_date':'采购日期',
            'purchase_cost':'采购价格',
            'order_number':'订单号',
            'reassignable':'是否可重复申请',
            'license_name':'授权人名称',
            'license_email':'授权人邮箱',
            'notes':'备注',
            'expiration_date':'到期日期',
            'termination_date':'终止日期', 
            'category_id':'分类Id', 
            'manufacturer_id':'制造商Id',
            'supplier_id':'供应商Id',
            'checkout_seats':'借出数量' } 

    export_serializer_class = ExportLicensesSerializer
    export_field_data = ['软件许可ID', '名称', '序列号','创建时间', '授权数量','采购日期',
                         '采购价格', '订单号','是否可重复申请','授权人名称','授权人邮箱','备注',
                         '到期日期','终止日期','分类Id', '制造商Id','供应商Id','借出数量']


'''
/kits/        GET     -显示所有
/kits/        post    -新增一个
/kits/{id}/   GET     -显示单个
/kits/{id}/   PUT     -编辑单个
/kits/{id}/   DELETE  -删除单个
'''
class KitsModelViewSet(CustomModelViewSet):
    '''
    套件模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Kits.objects.all()
    serializer_class = KitsSerializer
    create_serializer_class = KitsCreateUpdateSerializer
    update_serializer_class = KitsCreateUpdateSerializer
    filter_class = KitsFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    search_fields = ('name',)

    def add_assets(self,request: Request, *args, **kwargs):
        tag = request.data.get('tag', None)
        quantity = request.data.get('quantity',None)
        kit_id = request.data.get('kit', None)
        kit = Kits.objects.get(id=kit_id)
        id = request.data.get('id', None)
        if tag == "model":    # 资产型号
            model = Models.objects.get(id=id)
            KitsModels.objects.create(kit=kit,model=model,quantity=quantity,create_datetime=datetime.now(),update_datetime=datetime.now())
        if tag == "license":    # 软件授权
            license = Licenses.objects.get(id=id)
            KitsLicenses.objects.create(kit=kit,license=license,quantity=quantity,create_datetime=datetime.now(),update_datetime=datetime.now())
        if tag == "accessories":    # 附属品
            accessories = Accessories.objects.get(id=id)
            KitsAccessories.objects.create(kit=kit,accessory=accessories,quantity=quantity,create_datetime=datetime.now(),update_datetime=datetime.now())
        if tag == "consumables":    # 消耗品
            consumables = Consumables.objects.get(id=id)
            KitsConsumables.objects.create(kit=kit,consumables=consumables,quantity=quantity,create_datetime=datetime.now(),update_datetime=datetime.now())

        return SuccessResponse()    

    def get_assets(selft,request: Request):
        kit_id = request.query_params.get('kit', None)
        tag = request.query_params.get('tag', None)
        print(f"kit={kit_id},tag={tag}")
        if tag == "model":    # 资产型号
            queryset = KitsModels.objects.filter(kit_id=kit_id)
            serializer = KitsModelsSerializer(queryset, many=True)
            return SuccessResponse(serializer.data)
        if tag == "license":    # 软件授权
            queryset = KitsLicenses.objects.filter(kit_id=kit_id)
            serializer = KitsLicensesSerializer(queryset, many=True)
            return SuccessResponse(serializer.data)
        if tag == "accessories":    # 附属品
            queryset = KitsAccessories.objects.filter(kit_id=kit_id)
            serializer = KitsAccessoriesSerializer(queryset, many=True)
            return SuccessResponse(serializer.data)
        if tag == "consumables":    # 消耗品
            queryset = KitsConsumables.objects.filter(kit_id=kit_id)
            serializer = KitsConsumablesSerializer(queryset, many=True)
            return SuccessResponse(serializer.data)
        
        return SuccessResponse()


    def del_assets(selft,request: Request):
        id = request.query_params.get('id', None)
        tag = request.query_params.get('tag', None)
        print(f"kit={id},tag={tag}")
        if tag == "model":    # 资产型号
            KitsModels.objects.filter(id=id).delete()
        if tag == "license":    # 软件授权
            KitsLicenses.objects.filter(id=id).delete()
        if tag == "accessories":    # 附属品
            KitsAccessories.objects.filter(id=id).delete()
        if tag == "consumables":    # 消耗品
            KitsConsumables.objects.filter(id=id).delete()
        
        return SuccessResponse()


'''
/maintenances/        GET     -显示所有
/maintenances/        post    -新增一个
/maintenances/{id}/   GET     -显示单个
/maintenances/{id}/   PUT     -编辑单个
/maintenances/{id}/   DELETE  -删除单个
'''
class MaintenancesModelViewSet(CustomModelViewSet):
    '''
    资产维护模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Maintenances.objects.all()
    serializer_class = MaintenancesSerializer
    filter_class = MaintenancesFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    search_fields = ('title',)


'''
/uploads/        GET     -显示所有
/uploads/        post    -新增一个
/uploads/{id}/   GET     -显示单个
/uploads/{id}/   PUT     -编辑单个
/uploads/{id}/   DELETE  -删除单个
'''
class UploadsModelViewSet(CustomModelViewSet):
    '''
    资产维护模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Uploads.objects.all()
    serializer_class = UploadsSerializer
    filter_class = UploadsFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    search_fields = ('filename',)

'''
/locations/        GET     -显示所有
/locations/        post    -新增一个
/locations/{id}/   GET     -显示单个
/locations/{id}/   PUT     -编辑单个
/locations/{id}/   DELETE  -删除单个
'''
class LocationsModelViewSet(CustomModelViewSet):
    '''
    资产维护模型的CRUD视图
    '''
    permission_classes = [IsAuthenticated]
    queryset = Locations.objects.all()
    serializer_class = LocationsSerializer
    filter_class = LocationsFilter
    # extra_filter_backends = [DataLevelPermissionsFilter]
    search_fields = ('name',)

    import_serializer_class = ExportLocationsSerializer
    import_field_data = {
            'id':'位置ID', 
            'name':'位置名称',
            'create_datetime':'创建时间',
            'country':'国家',
            'province':'省份',
            'city':'城市',
            'district':'区',
            'address':'地址1',
            'address2':'地址2',
            'zip':'邮编',
            'ancestors':'关系图',
            'currency':'货币',
            'parent_id':'父ID',
            'manager_id':'管理员Id'
    }

    export_serializer_class = ExportLocationsSerializer
    export_field_data = ['位置ID', '位置名称', '创建时间', '国家', '省份',
                         '城市', '区','地址1','地址2','邮编',
                         '关系图','货币','父ID','管理员Id']

    def destroy(self, request, *args, **kwargs):
        try:
            super().destroy(request,*args,**kwargs)
        except ProtectedError:
            raise APIException(message='该位置已被关联使用,不能删除只能修改')

class UserCheckoutReportModelViewSet(CustomModelViewSet):
    """
    用户借出资产报表
    """
    permission_classes = [IsAuthenticated]
    queryset = UserCheckoutReport.objects.all()
    serializer_class = UserCheckoutReportSerializer
    filter_class = UserCheckoutReportFilter

class CategoryTotalReportModelViewSet(CustomModelViewSet):
    """
    分类统计报表
    """
    permission_classes = [IsAuthenticated]
    queryset = CategoryTotalReport.objects.all()
    serializer_class = CategoryTotalReportSerializer
    filter_class = CategoryTotalReportFilter


class ReportViewSet(GenericViewSet):

    def total(self,request):
        """
        总览报表
        """
        asset_num = Assets.objects.filter(deleted_datetime=None).count()
        component_num = Components.objects.filter(deleted_datetime=None).count()
        license_num = Licenses.objects.filter(deleted_datetime=None).count() 
        accessory_num = Accessories.objects.filter(deleted_datetime=None).count()
        consumable_num = Consumables.objects.filter(deleted_datetime=None).count()
        user_num = UserProfile.objects.count()
        return SuccessResponse(data={
            "asset_num":asset_num,
            "component_num":component_num,
            "license_num":license_num,
            "accessory_num":accessory_num,
            "consumable_num":consumable_num,
            "user_num":user_num
        })

    def assetStatus(self,request):
        """
        资产状态总览报表
        """
        result = AssetStatusReport.objects.all()
        result_list = AssetStatusReportSerializer(result, many=True).data
        return SuccessResponse(data=result_list)
    


